﻿from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader, Context
from django.core.paginator import ObjectPaginator, InvalidPage
from app.engine import models
from app.forum import models as models1
from app.engine import bforms
from app.base.coreXML import rawData
from google.appengine.api import users
from google.appengine.ext import db
from app.functions.funcs import render,split_tags,formate_time,gen_duration,retext,gencolor,genid,gen_quote
from app.functions import gviz_api
from app.base.auth import LoginUrl,ChkAuth,ChkAdmin,login_required,admin_required,member_required
from app.base.language import setEnLanguage,setCnLanguage
from google.appengine.api import memcache
import urllib

def index(request):
    greeting = LoginUrl()
    multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview','ca_admin'])
    payload = dict(greeting=greeting,multi_language=multi_language)
    return render('index.html',payload)

def adminCreatePost(request):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview',
                        'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp','ca_submit',
                        'ca_site_name','ca_site_summary','ca_dkp_manager','ca_site_language'])
        posts = models.Post.all()
        if request.method == 'POST':
            post = models.Post(title = request.POST.get('title').decode('utf-8'),
                                content = request.POST.get('content').decode('utf-8'),
                                author = users.get_current_user())
            post.put()
            return HttpResponseRedirect('/admin/post/')
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict(greeting=greeting,multi_language=multi_language,posts=posts)
    return render('adminCreatePost.html',payload)

def adminEditPost(request, post_id):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview',
                        'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp','ca_submit',
                        'ca_site_name','ca_site_summary','ca_dkp_manager','ca_site_language'])
        posts = models.Post.all()
        post = models.Post.get_by_id(int(post_id))
        if request.method == 'POST':
            post.title = request.POST.get('title').decode('utf-8')
            post.content = content = request.POST.get('content').decode('utf-8')
            post.put()
            return HttpResponseRedirect('/admin/post/')
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict(posts=posts,post=post,greeting=greeting,multi_language=multi_language)
    return render('adminCreatePost.html',payload)

@admin_required
def adminSiteConfig(request):
    greeting = LoginUrl()

    multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview',
                            'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp','ca_submit',
                            'ca_site_name','ca_site_summary','ca_dkp_manager','ca_site_language'])
    keyname = "wow-dkp-engine"
    site = models.SiteConfig.get_or_insert(keyname)
    if request.method == 'POST':
#        manager_list = []
        site_name = request.POST.get('name').decode('utf-8')
        site_summary = request.POST.get('summary').decode('utf-8')
        site_language = request.POST.get('language')
#        dkp_manager = request.POST.get('manager')
#        dkp_manager = dkp_manager.split(',')
#        for manager in dkp_manager:
#            manager_list.append(db.Email(manager))
        site.name = site_name
        site.summary = site_summary
#        site.manager = manager_list
        site.language = site_language
        site.put()
        if site.language == 'cn':
            setCnLanguage()
        elif site.language == 'en':
            setEnLanguage()
        else:
            pass
        return HttpResponseRedirect('/admin/site/')
    payload = dict(site=site,greeting=greeting,multi_language=multi_language)
    return render('adminSiteConfig.html', payload)

def adminCreateEvent(request):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        players = models.Players.all()
        multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview','ca_admin',
                                            'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp',
                                            'ca_event_title','ca_event_summary','ca_submit',
                                            'ca_warlock','ca_priest','ca_mage','ca_druid','ca_rogue','ca_shaman','ca_hunter','ca_paladin','ca_warrior','ca_deathknight'])
        if request.method == 'POST':
            user = users.get_current_user()
            members = request.POST.getlist('player')
            members_key = []
            members = models.Players.get(members)
            for member in members:
                members_key.append(member.key())
            event = models.EventData(
                                     title=request.POST.get('title').decode('utf-8'),
                                     summary=request.POST.get('summary').decode('utf-8'),
                                     members = members_key,
                                     author = user,
                                     multi_language = multi_language
                                     )
            event.event_put()
            return HttpResponseRedirect('/admin/events/%s' %event.key().id())
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict(players=players, multi_language=multi_language)
    return render('adminEventCreate.html', payload)

def adminImportEvent(request):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview','ca_admin',
                                            'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp','ca_event_content',
                                            'ca_event_title','ca_event_summary','ca_content','ca_submit'])
        if request.method == 'POST':
            user = users.get_current_user()
            title = request.POST.get('title').decode('utf-8')
            summary = request.POST.get('summary').decode('utf-8')
            content = request.POST.get('content').decode('utf-8')
            event = models.EventData(title=title,summary=summary,content=content,author=user)
            event.put()
            return HttpResponseRedirect('/admin/events/')
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict(multi_language=multi_language)
    return render('adminImportEvent.html', payload)

def adminGenEvent(request,event_id):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        event = models.EventData.get_by_id(int(event_id))
        data = event.content.encode('utf8')
        rawdata = rawData(data)
        rawdata.getEventStart()
        rawdata.getEventEnd()
        event.start = rawdata.start
        event.end = rawdata.end
        rawdata.getPlayersInfo()
        rawdata.getBossInfo()
        rawdata.getLootInfo()
        for player in rawdata.players:
            player_template = models.Players(
                                            player_name=player['player_name'],
                                            player_race=player['player_race'],
                                            player_level=player['player_level'],
                                            player_sex=player['player_sex'],
                                            player_class=player['player_class'],
                                            player_guild=player['player_guild']
                                            )
            r_player = models.Players.all().filter('player_name =',player_template.player_name)
            if r_player.count() == 0:
                player_template.put()
            else:
                player_template = r_player[0]
                player_template.player_name = player['player_name']
                player_template.player_race = player['player_race']
                player_template.player_level = player['player_level']
                player_template.player_sex = player['player_sex']
                player_template.player_class = player['player_class']
                player_template.player_guild = player['player_guild']
                player_template.put()
            if models.PlayerScore.all().filter('player =',player_template.key()).count() == 0:
                playerscore = models.PlayerScore(player=player_template.key())
                playerscore.put()
            if player_template.key() in event.members:
                pass
            else:
                event.members.append(player_template.key())
        event.content = None
        user = users.get_current_user()
        event.author = user
        event.event_put()
        
        for bosskill in rawdata.boss:
            bosskilled = models.ActionInEvent(title=bosskill['boss_name'],event=event.key(),summary="boss kill",score=bosskill['boss_score'])
            bosskilled.action_put()
        
        for loot in rawdata.loots:
            gear_player = models.Players.all().filter('player_name =', loot['loot_player'])
            gear_player = gear_player[0]
            geardata=models.GearData(
                                    event=event,
                                    gear_name=loot['loot_name'],
                                    gear_id=genid(loot['loot_id']),
                                    gear_color=gencolor(loot['loot_color']),
                                    gear_icon=loot['loot_icon'],
                                    gear_player=gear_player,
                                    gear_costs=loot['loot_costs'],
                                    gear_count=loot['loot_count']
                                    )
            geardata.gear_put()
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    return HttpResponseRedirect('/admin/events/%s' %event_id)

def adminListEvent(request):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview','ca_admin',
                                            'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp',
                                            'ca_number','ca_id','ca_title','ca_author','ca_date','ca_generate','ca_edit','ca_delete'])
        events = models.EventData.all()
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict(events=events,greeting=greeting,multi_language=multi_language)
    return render('adminEventList.html', payload)

def viewEventInfo(request,event_id):
    admin = False
    user = users.get_current_user()
    greeting = LoginUrl()
    if user:
        if users.is_current_user_admin():
            admin = True
        else:
            admin = False
    event = models.EventData.get_by_id(int(event_id))
    actions = models.ActionInEvent.all().filter('event =',event.key())
    actions_num = actions.count()
    loots = models.GearData.all().filter('event =',event.key())
    loots_num = loots.count()
    rewards = models.RewardInEvent.all().filter('event =',event.key())
    rewards_num = rewards.count()
    punishment = models.PunishmentInEvent.all().filter('event =',event.key())
    punishment_num = punishment.count()
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','ca_home','ca_event','ca_players','ca_class','ca_overview',
                                    'fa_forum_second_menu_players','fa_forum_second_menu_events','fa_forum_second_menu_class','fa_forum_second_menu_overview',
                                    'ca_num','ca_score','ca_summary','ca_realm','ca_start','ca_end',
                                    'ca_event_members','ca_event_actions','ca_event_reward','ca_event_punish',
                                    'ca_total','ca_edit','ca_delete','ca_choose_members','ca_add_actions',
                                    'ca_add_reward','ca_add_punish','ca_gear','ca_duration','ca_add_loot','ca_event_loot',
                                    'fa_forum_sider_lang_home',
                                    'fa_forum_sider_lang_register',
                                    'fa_forum_sider_lang_create_topic',
                                    'fa_forum_sider_lang_member_info',
                                    'fa_forum_sider_lang_signout',
                                    'fa_forum_sider_lang_signin'])
    players = models.Players.get(event.members)
    payload = dict(admin=admin,
                    event=event,
                    players=players,
                    loots=loots,
                    eventid=event_id,
                    actions=actions,
                    rewards=rewards,
                    punishment=punishment,
                    actions_num=actions_num,
                    loots_num=loots_num,
                    rewards_num=rewards_num,
                    punishment_num=punishment_num,
                    multi_language= multi_language,
                    page_type='dkp',
                    user=user,
                    greeting=greeting,
                    quotation=viewquote(),)
    return render('viewEventInfo.html',payload)

def viewEventsList(request):
    user = users.get_current_user()
    greeting = LoginUrl()
    events = models.EventData.all()
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','ca_home','ca_event','ca_players','ca_class','ca_overview',
                                        'fa_forum_second_menu_players','fa_forum_second_menu_events','fa_forum_second_menu_class','fa_forum_second_menu_overview',
                                        'ca_number','ca_title','ca_author','ca_date','ca_members',
                                        'fa_forum_sider_lang_home',
                                        'fa_forum_sider_lang_register',
                                        'fa_forum_sider_lang_create_topic',
                                        'fa_forum_sider_lang_member_info',
                                        'fa_forum_sider_lang_signout',
                                        'fa_forum_sider_lang_signin'])
    payload = dict(quotation=viewquote(),events=events,multi_language=multi_language,page_type='dkp',user=user,greeting=greeting)
    return render('viewEventsList.html', payload)

def adminEditEvent(request,event_id):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview','ca_admin',
                                            'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp','event_content',
                                            'ca_event_title','ca_event_summary','ca_content','ca_submit'])
        event = models.EventData.get_by_id(int(event_id))
        user = users.get_current_user()
        if request.method == 'POST':
            event.title = request.POST.get('title').decode('utf-8')
            event.summary = request.POST.get('summary').decode('utf-8')
            event.content = request.POST.get('content').decode('utf-8')
            event.author = user
            event.put()
            return HttpResponseRedirect('/admin/events')
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict(event=event,multi_language=multi_language)
    return render('adminImportEvent.html',payload)

def adminDeleteEvent(request,event_id):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        event = models.EventData.get_by_id(int(event_id))
        event.event_del()
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    return HttpResponseRedirect('/admin/events')

def adminAddAction(request,action_type,event_id):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview',
                                            'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp','ca_submit',
                                            'ca_action_title','ca_action_score','ca_action_summary',
                                            'ca_warlock','ca_priest','ca_mage','ca_druid','ca_rogue','ca_shaman','ca_hunter','ca_paladin','ca_warrior','ca_deathknight'])
        event = models.EventData.get_by_id(int(event_id))
        players = models.Players.get(event.members)
        if request.method == 'POST':
            members = []
            action_title = request.POST.get('title')
            action_summary = request.POST.get('summary')
            action_score = request.POST.get('score')
            members_list = request.POST.getlist('player')
            members_list_obj = models.Players.get(members_list)
            for player in members_list_obj:
                members.append(player.key())
            if action_type == 'action':
                action = models.ActionInEvent(event = event,
                                               title = action_title.decode('utf-8'),
                                               summary = action_summary.decode('utf-8'),
                                               score = int(action_score),
                                               players = members)
            elif action_type == 'reward':
                action = models.RewardInEvent(event = event,
                                               title = action_title.decode('utf-8'),
                                               summary = action_summary.decode('utf-8'),
                                               score = int(action_score),
                                               players = members)
            elif action_type == 'punishment':
                action = models.PunishmentInEvent(event = event,
                                               title = action_title.decode('utf-8'),
                                               summary = action_summary.decode('utf-8'),
                                               score = int(action_score),
                                               players = members)
            action.action_put()
            return HttpResponseRedirect('/admin/events/%s/' %event.key().id())
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict(players=players,multi_language=multi_language)
    return render('adminEditAction.html', payload)

def adminEditAction(request,action_type,action_id):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview',
                                            'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp','ca_submit',
                                            'ca_action_title','ca_action_score','ca_action_summary',
                                            'ca_warlock','ca_priest','ca_mage','ca_druid','ca_rogue','ca_shaman','ca_hunter','ca_paladin','ca_warrior','ca_deathknight'])
    
        if action_type == 'action':
            action = models.ActionInEvent.get_by_id(int(action_id))
        elif action_type == 'reward':
            action = models.RewardInEvent.get_by_id(int(action_id))
        elif action_type == 'punishment':
            action = models.PunishmentInEvent.get_by_id(int(action_id))
        oldlist = action.players
        oldscore = action.score
        event = models.EventData.get(action.event.key())
        players = models.Players.get(event.members)
        players_obj = []
        for player in players:
            if player.key() in action.players:
                player.checkbox = True
            else:
                player.checkbox = False
            players_obj.append(player)

        if request.method == 'POST':
            members = []
            action_title = request.POST.get('title')
            action_summary = request.POST.get('summary')
            action_score = int(request.POST.get('score'))
            members_list = request.POST.getlist('player')
            members_list_obj = models.Players.get(members_list)
            for player in members_list_obj:
                members.append(player.key())
            action.title = action_title.decode('utf-8')
            action.summary = action_summary.decode('utf-8')
            action.score = action_score
            action.players = members
            action.action_edit(oldlist,oldscore)
            return HttpResponseRedirect('/admin/events/%s/' %event.key().id())
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict(players=players_obj,action=action,multi_language=multi_language)
    return render('adminEditAction.html', payload)
    
def adminDeleteAction(request,action_type,action_id):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        if action_type == 'action':
            action = models.ActionInEvent.get_by_id(int(action_id))
        elif action_type == 'reward':
            action = models.RewardInEvent.get_by_id(int(action_id))
        elif action_type == 'punishment':
            action = models.PunishmentInEvent.get_by_id(int(action_id))
        event = models.EventData.get(action.event.key())
        action.action_del()
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    return HttpResponseRedirect('/admin/events/%s/' %event.key().id())

def viewPlayerInfo(request,player_key):
    user = users.get_current_user()
    greeting = LoginUrl()
    player = models.Players.all().filter('player_name =', player_key.decode('utf8'))
    player = player[0]
    gears = models.GearData.all().filter('gear_player =', player.key())
    events = models.EventData.all()
    playerscore = memcache.get('cache_score').filter('player =', player.key())
    playerscore = playerscore[0]
    player_in_events = []
    for event in events:
        if player.key() in event.members:
            player_in_events.append(event)
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','ca_home','ca_event','ca_players','ca_class','ca_overview',
                            'fa_forum_second_menu_players','fa_forum_second_menu_events','fa_forum_second_menu_class','fa_forum_second_menu_overview',
                            'ca_race','ca_number','ca_attend','ca_earn','ca_adjust','ca_reward',
                            'ca_punish','ca_current','ca_cost','ca_gear',
                            'ca_human','ca_dwraf','ca_nightelf','ca_gnome','ca_draenei',
                            'ca_troll','ca_undead','ca_tauren','ca_bloodelf','ca_orc',
                            'ca_warrior','ca_paladin','ca_priest','ca_rogue','ca_mage','ca_warlock','ca_druid','ca_hunter','ca_shaman','ca_deathknight',
                            'fa_forum_sider_lang_home',
                            'fa_forum_sider_lang_register',
                            'fa_forum_sider_lang_create_topic',
                            'fa_forum_sider_lang_member_info',
                            'fa_forum_sider_lang_signout',
                            'fa_forum_sider_lang_signin'])
    payload = dict(page_type='dkp',
                    side_type='score',
                    player=player,
                    gears=gears,
                    events=player_in_events,
                    playerscore=playerscore,
                    multi_language=multi_language,
                    user=user,greeting=greeting,
                    quotation=viewquote(),
                    )
    return render('viewPlayerInfo.html', payload)

def overviewScore(request):
    user = users.get_current_user()
    greeting = LoginUrl()
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','fa_forum_sider_lang_home',
                                        'fa_forum_second_menu_players','fa_forum_second_menu_events','fa_forum_second_menu_class','fa_forum_second_menu_overview',
                                        'fa_forum_sider_lang_register',
                                        'fa_forum_sider_lang_create_topic',
                                        'fa_forum_sider_lang_member_info',
                                        'fa_forum_sider_lang_signout',
                                        'fa_forum_sider_lang_signin'])
    description = {"name": ("string", "Name"),
                   "earned": ("number", "Earned"),
                   "adjust": ("number", "Adjust"),
                   "rewards": ("number", "Rewards"),
                   "punishment": ("number", "Punishment"),
                   "cost": ("number", "Costs"),
                   "current": ("number", "Current"),}
    data = []
    playersscore = memcache.get('cache_score')
    for playerscore in playersscore:
        player_dict = {
                        "name":playerscore.player.player_name,
                        "earned":playerscore.earn,
                        "adjust":playerscore.adjust,
                        "rewards":playerscore.reward,
                        "punishment":playerscore.punishment,
                        "cost":playerscore.cost,
                        "current":playerscore.current_score(),
                       }
        data.append(player_dict)
    data_table = gviz_api.DataTable(description)
    data_table.LoadData(data)
    json = data_table.ToJSon(columns_order=("name", "earned","adjust","rewards","punishment","cost","current"))
    payload = dict(quotation=viewquote(),json=json,multi_language=multi_language,page_type='dkp',user=user,greeting=greeting)
    return render('viewPlayerScoreTable.html',payload)
    

def overviewClassImage(request):
    players = models.Players.all().count()
    warlock = models.Players.all().filter('player_class','WARLOCK').count()
    mage = models.Players.all().filter('player_class','MAGE').count()
    priest = models.Players.all().filter('player_class','PRIEST').count()
    rogue = models.Players.all().filter('player_class','ROGUE').count()
    druid = models.Players.all().filter('player_class','DRUID').count()
    shaman = models.Players.all().filter('player_class','SHAMAN').count()
    hunter = models.Players.all().filter('player_class','HUNTER').count()
    paladin = models.Players.all().filter('player_class','PALADIN').count()
    warrior = models.Players.all().filter('player_class','WARRIOR').count()
    deadknight = models.Players.all().filter('player_class','DEADKNIGHT').count()
    payload = dict(players=players,
                   warlock=warlock,
                   mage=mage,
                   priest=priest,
                   rogue=rogue,
                   druid=druid,
                   shaman=shaman,
                   hunter=hunter,
                   paladin=paladin,
                   warrior=warrior,
                   deadknight=deadknight,
                   quotation=viewquote(),)
    return render('viewGuildClassPic.html',payload)

def overviewClassChart(request):
    user = users.get_current_user()
    greeting = LoginUrl()
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin',
                                        'fa_forum_second_menu_players','fa_forum_second_menu_events','fa_forum_second_menu_class','fa_forum_second_menu_overview',
                                        'ca_warlock','ca_priest','ca_mage','ca_druid','ca_rogue','ca_shaman','ca_hunter','ca_paladin','ca_warrior','ca_deathknight',
                                        'fa_forum_sider_lang_home',
                                        'fa_forum_sider_lang_register',
                                        'fa_forum_sider_lang_create_topic',
                                        'fa_forum_sider_lang_member_info',
                                        'fa_forum_sider_lang_signout',
                                        'fa_forum_sider_lang_signin'])
    warlock = memcache.get('cache_score_warlock')
    mage = memcache.get('cache_score_mage')
    priest = memcache.get('cache_score_priest')
    rogue = memcache.get('cache_score_rogue')
    druid = memcache.get('cache_score_druid')
    shaman = memcache.get('cache_score_shaman')
    hunter = memcache.get('cache_score_hunter')
    paladin = memcache.get('cache_score_paladin')
    warrior = memcache.get('cache_score_warrior')
    deadknight = memcache.get('cache_score_deathknight')
    description = {"class": ("string", "Class"),"count": ("number", "Count"),}
    data = [{"class": multi_language['ca_warlock'].decode('utf-8'), "count": len(warlock)},
            {"class": multi_language['ca_mage'].decode('utf-8'), "count": len(mage)},
            {"class": multi_language['ca_priest'].decode('utf-8'), "count": len(priest)},
            {"class": multi_language['ca_rogue'].decode('utf-8'), "count": len(rogue)},
            {"class": multi_language['ca_druid'].decode('utf-8'), "count": len(druid)},
            {"class": multi_language['ca_shaman'].decode('utf-8'), "count": len(shaman)},
            {"class": multi_language['ca_hunter'].decode('utf-8'), "count": len(hunter)},
            {"class": multi_language['ca_paladin'].decode('utf-8'), "count": len(paladin)},
            {"class": multi_language['ca_warrior'].decode('utf-8'), "count": len(warrior)},
            {"class": multi_language['ca_deathknight'].decode('utf-8'), "count": len(deadknight)},]

    # Loading it into gviz_api.DataTable
    data_table = gviz_api.DataTable(description)
    data_table.LoadData(data)
    # Creating a JSon string
    json = data_table.ToJSon(columns_order=("class", "count"))
    payload = dict(side_type='score',quotation=viewquote(),json=json,multi_language=multi_language,page_type='dkp',user=user,greeting=greeting)
    return render('viewGuildClass.html',payload)

def adminImportAdjust(request):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview','ca_admin',
                                            'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp','ca_submit'])
        if request.method == 'POST':
            data = request.POST.get('content')
            players = retext(data)
            for player in players.items():
                rawplayer = models.Players.all().filter('player_name =', player[0].decode('utf-8'))
                if rawplayer.count() == 0:
                    r_player = models.Players(player_name=player[0].decode('utf-8'))
                    r_player.put()
                    playerscore = models.PlayerScore.all().filter('player =',r_player.key())
                    if playerscore.count() == 0:
                        playerscore = models.PlayerScore(player=r_player.key(),adjust=int(player[1]))
                        playerscore.put()
                    else:
                        playerscore = playerscore[0]
                        playerscore.adjust = int(player[1])
                        playerscore.put()
                else:
                    rawplayer = rawplayer[0]
                    playerscore = models.PlayerScore.all().filter('player =',rawplayer.key())
                    if playerscore.count() == 0:
                        playerscore = models.PlayerScore(player=rawplayer.key(),adjust=int(player[1]))
                        playerscore.put()
                    else:
                        playerscore = playerscore[0]
                        playerscore.adjust = int(player[1])
                        playerscore.put()
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict(multi_language=multi_language)
    return render('adminImportAdjust.html', payload)

def adminExportCurrent(request):
    data = models.PlayerScore.all()
    response = HttpResponse(mimetype='application/x-python')
    response['Content-Disposition'] = 'attachment;filename=%s.lua' %'dkp_list'
    t = loader.get_template('adminExportCurrent.html')
    c = Context({
        'data': data,
    })
    response.write(t.render(c))
    return response

def adminChoosePlayers(request, event_id):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview',
                                            'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp','ca_submit',
                                            'ca_warlock','ca_priest','ca_mage','ca_druid','ca_rogue','ca_shaman','ca_hunter','ca_paladin','ca_warrior','ca_deathknight'])
        event = models.EventData.get_by_id(int(event_id))
        member_list = event.members
        players = models.Players.all().order('player_class')
        all_players=[]
        for player in players:
            if player.key() in event.members:
                player.checkbox = True
            else:
                player.checkbox = False
            all_players.append(player)
        if request.method == 'POST':
            choosed_players_key = []
            post_players = request.POST.getlist('player')
            choosed_players_in_event = models.Players.get(post_players)
            for player in choosed_players_in_event:
                choosed_players_key.append(player.key())
            event.members = choosed_players_key
            event.update_members(member_list)
            return HttpResponseRedirect('/admin/events/members/%s/' %event_id)
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict(players=all_players,multi_language=multi_language)
    return render('adminChoosePlayers.html', payload)

def dropdata(request):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        for player in models.PlayerScore.all():
            player.delete()
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    return HttpResponseRedirect('/')

def adminListPlayers(request,page=1,orderby=None):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview','ca_admin',
                                        'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp',
                                        'ca_players','ca_gender','ca_class','ca_race','ca_level','ca_guild','ca_edit','ca_delete',
                                        'ca_prev','ca_next'])
        try:
            page = int(page)-1
        except:
            page = 0
        show_prev = False
        show_next = False
        all_players = models.Players.all()
        paginator = ObjectPaginator(all_players,100)
        if page >= paginator.pages:
            page = paginator.pages - 1
        players=paginator.get_page(page)
        pages=range(1,paginator.pages+1)
        show_prev = paginator.has_previous_page(page)
        show_next = paginator.has_next_page(page)
        page=page+1
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict(players=players,
                   show_prev=show_prev,
                   show_next=show_next,
                   page=page,
                   pages=pages,
                   prev=page-1,
                   next=page+1,
                   multi_language=multi_language)
    return render('adminListPlayer.html',payload)

def adminEditPlayer(request,player_id):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview','ca_admin',
                                        'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp','ca_submit',
                                        'ca_player_name','ca_player_guild','ca_player_level','ca_adjust_score','ca_player_gender','ca_player_race','ca_player_class','ca_boy','ca_girl',
                                        'ca_warlock','ca_priest','ca_mage','ca_druid','ca_rogue','ca_shaman','ca_hunter','ca_paladin','ca_warrior','ca_deathknight',
                                        'ca_human','ca_gnome','ca_draenei','ca_nightelf','ca_dwarf','ca_orc','ca_undead','ca_troll','ca_tauren','ca_bloodelf'])
        player = models.Players.get_by_id(int(player_id))
        playerscore = models.PlayerScore.all().filter('player =',player.key())
        playerscore = playerscore[0]
        if request.method == 'POST':
            player.player_name = request.POST.get('player_name').decode('utf-8')
            player.player_sex = request.POST.get('player_sex')
            player.player_class = request.POST.get('player_class')
            player.player_race = request.POST.get('player_race')
            player.player_guild = request.POST.get('player_guild').decode('utf-8')
            player.player_level = request.POST.get('player_level')
            player_adjust = request.POST.get('player_adjust')
            player_adjust = int(player_adjust)
            player.player_edit(player_adjust)
            return HttpResponseRedirect('/pub/players/%s' %player.player_name.encode('utf-8'))
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict(player=player,playerscore=playerscore,multi_language=multi_language)
    return render('adminPlayerEdit.html',payload)

def adminDeletePlayer(request,player_id):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        player = models.Players.get_by_id(int(player_id))
        player.player_del()
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    return HttpResponseRedirect('/admin/players')

def adminAddPlayer(request):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        if request.method == 'POST':
            player = model.Players(
                                    player_name = request.POST.get('player_name').decode('utf-8'),
                                    player_sex = request.POST.get('player_sex'),
                                    player_class = request.POST.get('player_class'),
                                    player_race = request.POST.get('player_race'),
                                    player_guild = request.POST.get('player_guild').decode('utf-8'),
                                    player_level = request.POST.get('player_level')
                                    )
            player_adjust = request.POST.getlist('player_adjust')
            player_adjust = int(player_adjust)
            player.player_put(player_adjust)
            return HttpResponseRedirect('/pub/players/%s' %player.player_name.encode('utf-8'))
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict()
    return render('adminPlayerEdit.html',payload)

def adminDeletePlayer(request,player_id):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        player = models.Players.get_by_id(int(player_id))
        player.player_del()
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    return HttpResponseRedirect('/admin/players')

def adminEditGear(request,gear_id):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview','ca_admin',
                                'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp','ca_submit',
                                'ca_gear_name','ca_gear_id','ca_gear_icon','ca_gear_count','ca_gear_cost','ca_gear_color','ca_gear_owner',
                                'ca_poor','ca_common','ca_uncommon','ca_rare','ca_epic','ca_legendary','ca_heirloom',
                                'ca_warlock','ca_priest','ca_mage','ca_druid','ca_rogue','ca_shaman','ca_hunter','ca_paladin','ca_warrior','ca_deathknight',])
        gear = models.GearData.get_by_id(int(gear_id))
        event = gear.event
        players = models.Players.get(event.members)
        all_players = []
        for player in players:
            if player.key() == gear.gear_player.key():
                player.checkbox = True
            else:
                player.checkbox = False
            all_players.append(player)
        oldcost = gear.gear_costs
        oldowner = gear.gear_player
        if request.method == 'POST':
            gear.gear_name = request.POST.get('gear_name').decode('utf-8')
            gear.gear_id = request.POST.get('gear_id')
            gear.gear_color = request.POST.get('gear_color')
            gear.gear_icon = request.POST.get('gear_icon')
            gear_player = request.POST.get('player')
            gear_player = models.Players.get(gear_player)
            gear.gear_player = gear_player.key()
            gear.gear_costs = int(request.POST.get('gear_costs'))
            gear.gear_edit(oldcost,oldowner)
            return HttpResponseRedirect('/admin/events/%s' %event.key().id())
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict(players=all_players,gear=gear,multi_language=multi_language)
    return render('adminGearEdit.html',payload)


def adminAddGear(request,event_id):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        multi_language = memcache.get_multi(['ca_home','ca_event','ca_players','ca_class','ca_overview','ca_admin',
                                        'ca_site_config','ca_event_manage','ca_player_manage','ca_create_event','ca_import_event','ca_import_dkp','ca_submit',
                                        'ca_gear_name','ca_gear_id','ca_gear_icon','ca_gear_count','ca_gear_cost','ca_gear_color','ca_gear_owner',
                                        'ca_poor','ca_common','ca_uncommon','ca_rare','ca_epic','ca_legendary','ca_heirloom',
                                        'ca_warlock','ca_priest','ca_mage','ca_druid','ca_rogue','ca_shaman','ca_hunter','ca_paladin','ca_warrior','ca_deathknight',])
        event = models.EventData.get_by_id(int(event_id))
        all_players=models.Players.get(event.members)
        if request.method == 'POST':
            gear = models.GearData()
            gear.event = event.key()
            gear.gear_name = request.POST.get('gear_name').decode('utf-8')
            gear.gear_id = request.POST.get('gear_id')
            gear.gear_color = request.POST.get('gear_color')
            gear.gear_icon = request.POST.get('gear_icon')
            gear.gear_player = request.POST.get('player').key()
            gear.gear_level = request.POST.get('player_level')
            gear.gear_costs = int(request.POST.get('gear_costs'))
            gear.gear_put()
            return HttpResponseRedirect('/admin/events/%s' %event.key().id())
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    payload = dict(players=all_players,multi_language=multi_language)
    return render('adminGearEdit.html',payload)

def adminDeleteGear(request,gear_id):
    greeting = LoginUrl()
    admin = ChkAdmin()
    if admin == 0:
        gear = models.GearData.get_by_id(int(gear_id))
        gear.gear_del()
        return HttpResponseRedirect('/admin/events/%s' %gear.event.key().id())
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    return HttpResponseRedirect('/admin/players')

def viewPlayerScore(request,page=1):
    user = users.get_current_user()
    greeting = LoginUrl()
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','ca_home','ca_event','ca_players','ca_class','ca_overview','ca_admin',
                                    'fa_forum_second_menu_players','fa_forum_second_menu_events','fa_forum_second_menu_class','fa_forum_second_menu_overview',
                                    'ca_race','ca_number','ca_attend','ca_earn','ca_adjust','ca_reward',
                                    'ca_punish','ca_current','ca_cost','ca_next','ca_prev',
                                    'ca_warlock','ca_priest','ca_mage','ca_druid','ca_rogue','ca_shaman','ca_hunter','ca_paladin','ca_warrior','ca_deathknight',
                                    'fa_forum_sider_lang_home',
                                    'fa_forum_sider_lang_register',
                                    'fa_forum_sider_lang_create_topic',
                                    'fa_forum_sider_lang_member_info',
                                    'fa_forum_sider_lang_signout',
                                    'fa_forum_sider_lang_signin'])
    try:
        page = int(page)-1
    except:
        page = 0
    show_prev = False
    show_next = False
    all_players = memcache.get('cache_score')
    paginator = ObjectPaginator(all_players,40)
    if page >= paginator.pages:
        page = paginator.pages - 1
    players=paginator.get_page(page)
    pages=range(1,paginator.pages+1)
    show_prev = paginator.has_previous_page(page)
    show_next = paginator.has_next_page(page)
    page=page+1
    payload = dict(billboard=players,
                   show_prev=show_prev,
                   show_next=show_next,
                   page=page,
                   pages=pages,
                   prev=page-1,
                   next=page+1,
                   multi_language=multi_language,
                   page_type='dkp',
                   side_type='score',
                   user=user,greeting=greeting,
                   quotation=viewquote())
    return render('viewPlayerScore.html', payload)

def viewPlayerScoreBy(request,player_class):
    user = users.get_current_user()
    greeting = LoginUrl()
    if player_class == '9':
        players = memcache.get('cache_score_warlock')
    elif player_class == '5':
        players = memcache.get('cache_score_priest')
    elif player_class == '8':
        players = memcache.get('cache_score_mage')
    elif player_class == '11':
        players = memcache.get('cache_score_druid')
    elif player_class == '4':
        players = memcache.get('cache_score_rogue')
    elif player_class == '7':
        players = memcache.get('cache_score_shaman')
    elif player_class == '3':
        players = memcache.get('cache_score_hunter')
    elif player_class == '2':
        players = memcache.get('cache_score_paladin')
    elif player_class == '1':
        players = memcache.get('cache_score_warrior')
    elif player_class == '6':
        players = memcache.get('cache_score_deathknight')
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','ca_home','ca_event','ca_players','ca_class','ca_overview',
                                'fa_forum_second_menu_players','fa_forum_second_menu_events','fa_forum_second_menu_class','fa_forum_second_menu_overview',
                                'ca_race','ca_number','ca_attend','ca_earn','ca_adjust','ca_reward',
                                'ca_punish','ca_current','ca_cost',
                                'ca_warlock','ca_priest','ca_mage','ca_druid','ca_rogue','ca_shaman','ca_hunter','ca_paladin','ca_warrior','ca_deathknight',
                                'fa_forum_sider_lang_home',
                                'fa_forum_sider_lang_register',
                                'fa_forum_sider_lang_create_topic',
                                'fa_forum_sider_lang_member_info',
                                'fa_forum_sider_lang_signout',
                                'fa_forum_sider_lang_signin'])
    payload = dict(side_type='score',quotation=viewquote(),billboard=players,multi_language=multi_language,page_type='dkp',user=user,greeting=greeting)
    return render('viewPlayerScore.html', payload)

def adminClassMemcache(request):
    admin = ChkAdmin()
    if admin == 0:
        try:
            setClassCache()
        except:
            pass
    else:
        return HttpResponseRedirect('%s' %users.create_login_url("/"))
    return HttpResponseRedirect('/admin/site')

def setClassCache():
    warlock = []
    priest = []
    mage = []
    druid = []
    rogue = []
    hunter = []
    shaman = []
    paladin = []
    warrior = []
    deathknight = []

    for playerscore in memcache.get('cache_score'):
        if playerscore.player.player_class == '9':
            warlock.append(playerscore)
        elif playerscore.player.player_class == '5':
            priest.append(playerscore)
        elif playerscore.player.player_class == '8':
            mage.append(playerscore)
        elif playerscore.player.player_class == '11':
            druid.append(playerscore)
        elif playerscore.player.player_class == '4':
            rogue.append(playerscore)
        elif playerscore.player.player_class == '7':
            shaman.append(playerscore)
        elif playerscore.player.player_class == '3':
            hunter.append(playerscore)
        elif playerscore.player.player_class == '2':
            paladin.append(playerscore)
        elif playerscore.player.player_class == '1':
            warrior.append(playerscore)
        elif playerscore.player.player_class == '6':
            deathknight.append(playerscore)

    memcache.set('cache_score_warlock',warlock)
    memcache.set('cache_score_priest',priest)
    memcache.set('cache_score_mage',mage)
    memcache.set('cache_score_druid',druid)
    memcache.set('cache_score_rogue',rogue)
    memcache.set('cache_score_shaman',shaman)
    memcache.set('cache_score_hunter',hunter)
    memcache.set('cache_score_paladin',paladin)
    memcache.set('cache_score_warrior',warrior)
    memcache.set('cache_score_deathknight',deathknight)

def viewquote():
    quotations = models1.Quotations.all()
    num = quotations.count()
    quotation = quotations.fetch(1,gen_quote(num))
    quotation = quotation[0].quotation
    return quotation